package com.helper.pdf;

import com.aspose.cells.*;
import com.aspose.words.Document;
import javafx.print.Paper;

import java.io.*;

public class PdfUtil {

    /**
     * excel文件导出为PDF文件
     * paperSize
     *
     * @see com.aspose.cells.PaperSizeType
     */
    public static void excelToPdf(String sourceAddress, String targeAddress, Integer paper) {
        FileOutputStream fileOutputStream = null;
        if (!getLicense()) {
            System.out.println("非法------------");
            return;
        }
        File file = new File(targeAddress);
        try {
            Workbook wb = new Workbook(sourceAddress);
            for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
                Worksheet sheet = wb.getWorksheets().get(i);
                if (null != paper) {
                    sheet.getPageSetup().setPaperSize(paper);
                }
            }
            fileOutputStream = new FileOutputStream(file);
            wb.save(fileOutputStream, com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * word文件导出为PDF文件
     */
    public static void wordToPdf(String sourceAddress, String targeAddress) {
        if (!getLicense()) {
            return;
        }
        try {
            File file = new File(targeAddress);
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(sourceAddress);
            //全⾯⽀持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, com.aspose.words.SaveFormat.PDF);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Gets license //获取认证，去除水印
     *
     * @return the license
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            //这个文件应该是类似于密码验证(证书？)，用于获得去除水印的权限
            InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
